//
//  SAStageEventManager.m
//  GameFrame
//
//  Created by Hiroshi Nomura on 2013/11/22.
//  Copyright (c) 2013年 Hiroshi Nomura. All rights reserved.
//

#import "SAEventManager.h"

@interface SAEventManager()
{
 	NSMutableArray* eventQueueForProcess;
	NSMutableArray* eventQueueForPost;
    NSMutableArray* listenerList;
}
@property(retain)NSMutableArray* eventQueueForProcess;
@property(retain)NSMutableArray* eventQueueForPost;
@property(retain)NSMutableArray* listenerList;

@end


@implementation SAEventManager

int CANCEL_FLAG = 0;
static const int LISTENER_OBJECTS_MAX_SIZE = 256;

@synthesize eventQueueForProcess;
@synthesize eventQueueForPost;
@synthesize listenerList;

-(id)initWithCapacity:(int)capacity{
	if (self = [super init]){
		self.eventQueueForPost		= [[NSMutableArray alloc] initWithCapacity:capacity];
		self.eventQueueForProcess	= [[NSMutableArray alloc] initWithCapacity:capacity];
        
        self.listenerList = [[NSMutableArray alloc] initWithCapacity:SAEVENT_TYPE_SIZE];
        for (int i=0; i<SAEVENT_TYPE_SIZE; i++)
        {
            NSMutableArray* objectArray = [[NSMutableArray alloc] initWithCapacity:LISTENER_OBJECTS_MAX_SIZE];
            [self.listenerList addObject:objectArray];
        }
	}
	return self;
}

-(void)dispatchEvent
{    
    while (eventQueueForProcess.count > 0)
    {
        SAEventMessage* message = (__bridge SAEventMessage*)[self.eventQueueForProcess lastObject];
        [self.eventQueueForProcess removeLastObject];
    }
    
    /*
	dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
	dispatch_async(globalQueue,
				   ^{
					   while (CANCEL_FLAG == 0 && eventQueueForProcess.count > 0) {
						   SAStageEventMessage* message = [eventQueueForProcess lastObject];
						   [eventQueueForProcess removeLastObject];
						   //NSLog(@"%@", message.eventMessage);
					   }
				   });
    */
}

-(void)swapEventQueue
{
    if (self.eventQueueForProcess.count > 0)
    {
		[self.eventQueueForProcess removeAllObjects];
		
	}
	NSMutableArray* temp = self.eventQueueForPost;
	self.eventQueueForPost = self.eventQueueForProcess;
	self.eventQueueForProcess = temp;
}

-(void)registerEventListener:(id<SAEventClientInterface>*)listener type:(SAEventType)type
{
    //[self.listenerList addObject:listener];
}

-(void)unregisterEventListener:(id<SAEventClientInterface>*)listener type:(SAEventType)type
{
    
}

-(void)sendEvent:(id<SAEventClientInterface>*)sender message:(SAEventMessage*)message;
{
    
}

@end
